package com.xiaol.business.service.user.impl;

import com.github.pagehelper.PageHelper;
import com.xiaol.business.mapper.UserMapper;
import com.xiaol.business.model.User;
import com.xiaol.business.service.user.UserService;
import com.xiaol.framework.enums.ResultEnum;
import com.xiaol.framework.exception.UserException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service(value = "userService")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;  //这里会报错，但是并不会影响

    @Override
    public int addUser(User user) {
        return userMapper.insertSelective(user);
    }

    @Override
    public int deleteUserById(Integer userId) {
        return userMapper.deleteByPrimaryKey(userId);
    }

    @Override
    public int updateUserById(User user) {
        return userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public User queryUserById(Integer userId) {
        return userMapper.selectByPrimaryKey(userId);
    }

    @Override
    public List<User> queryUserList(){
        return userMapper.queryUserList();
    }

    /*
    * 分页插件pagehelper
    * pageNum 开始页数
    * pageSize 每页显示的数据条数
    * */
    @Override
    public List<User> queryUserByPage(Integer pageNum, Integer pageSize) {
        //将参数传给这个方法就可以实现物理分页了
        PageHelper.startPage(pageNum, pageSize);
        return userMapper.queryUserByPage();
    }

    @Override
    @Transactional
    public boolean transactionTest(){
        User user1 = new User();
        user1.setUserName("1");
        user1.setPassword("1");
        user1.setPhone("1");
        userMapper.insertSelective(user1);

        if(true){
            throw new UserException(ResultEnum.UNKONW_ERROR);
        }

        User user2 = new User();
        user2.setUserName("2");
        user2.setPassword("2");
        user2.setPhone("2");
        userMapper.insertSelective(user2);
        return true;
    }
}
